<template>
  <div>
    <el-card class="login-form-layout">
      <el-form
        autoComplete="on"
        :model="Form"
        :rules="Rules"
        ref="Form"
        label-position="left"
      >
        <div style="text-align: center">
          <svg-icon
            icon-class="login-mall"
            style="width: 56px;height: 56px;color: #409EFF"
          ></svg-icon>
        </div>
        <h2 class="login-title color-main">ymall-web-mall</h2>
        <el-form-item prop="username">
          <el-input
            id="username"
            name="username"
            type="text"
            v-model="Form.username"
            autoComplete="on"
            placeholder="请输入用户名"
            class="input-bg"
            prefix-icon="iconfont icon-user color-main"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            id="password"
            name="password"
            v-model="Form.password"
            autoComplete="on"
            placeholder="请输入密码"
            class="input-bg"
            prefix-icon="iconfont icon-password color-main"
            show-password
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="verifyCode">
          <el-input
            id="verifyCode"
            name="verifyCode"
            v-model="Form.verifyCode"
            autoComplete="on"
            placeholder="请输入验证码"
            prefix-icon="iconfont icon-verify color-main"
            class="input-bg"
          >
            <div
              slot="append"
              class="verify flex flex-align-center flex-justify-center"
              @click.stop="getVerifyCode"
            >
              {{ verify_display }}
            </div>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 60px">
          <el-button
            style="width: 100%"
            type="primary"
            :loading="loading"
            @click.native.prevent="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <img :src="login_center_bg" class="login-center-layout" />
  </div>
</template>

<script>
import { setSupport, getSupport, SupportUrl } from "@/utils/support";
import login_center_bg from "@/assets/images/login_center_bg.png";
import { login, register } from "@/api/login";
import { checkPhone } from "@/utils/utils";
import dateformat from "@/utils/date";

export default {
  name: "register",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("密码不能小于3位"));
      } else {
        callback();
      }
    };
    return {
      totalSeconds: 0,
      Form: {
        username: "",
        password: "",
        verifyCode: ""
      },
      Rules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ]
      },
      loading: false,
      pwdType: "password",
      login_center_bg,
      verify_display: "获取验证码"
    };
  },
  watch: {
    totalSeconds(nv, ov) {
      if (nv === 0) {
        this.verify_display = "获取验证码";
      } else {
        this.verify_display = `${nv}s后获取`;
      }
    }
  },
  methods: {
    countDown(deadline, duration = 1000) {
      let arr = deadline.split(/[^0-9]/);
      let deadTime = new Date(
        arr[0],
        arr[1] - 1,
        arr[2],
        arr[3],
        arr[4],
        arr[5]
      );
      let deadTimeMs = deadTime.getTime();
      let now = new Date();
      let countdown = deadTimeMs - now.getTime();
      if (countdown <= 0) {
        return;
      }
      let { day, hour, minute, second } = this.formatCountDown(countdown);
      this.day = day;
      this.hour = hour;
      this.minute = minute;
      this.second = second;
      this.timer = setTimeout(() => {
        this.totalSeconds = parseInt(countdown / 1000);
        this.countDown(deadline);
      }, duration);
    },

    formatCountDown(microSecond) {
      // 倒计时总秒数
      let second = Math.floor(microSecond / 1000);
      // 小时
      let hour = Math.floor(second / 3600);
      // 天
      let day = 0;
      if (hour >= 24) {
        // 如果小时大于24，计算出天和小时
        day = parseInt(hour / 24);
        hour %= 24;
      }
      // 分钟
      let minute = this.fillZeroPrefix(
        Math.floor((second - (day * 24 + hour) * 3600) / 60)
      );
      // 秒
      let sec = this.fillZeroPrefix(second % 60);
      return {
        day: this.fillZeroPrefix(day),
        hour: this.fillZeroPrefix(hour),
        minute,
        second: sec
      };
    },
    fillZeroPrefix(num) {
      // 位数补0
      return num < 10 ? "0" + num : num.toString();
    },
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
    async getVerifyCode() {
      this.$refs.Form.validate(async valid => {
        if (valid) {
          try {
            // await verify({
            //   phone: this.Form.phone
            // });
            this.countDown(dateformat.addSeconds(120));
            this.$message({
              message: "验证码发送成功",
              type: "success"
            });
          } catch (e) {
            this.$message.error(e);
          }
        } else {
          this.$message.error("电话号码错误");
          return false;
        }
      });
    },
    handleRegister() {
      this.$refs.Form.validate(async valid => {
        if (valid) {
          this.loading = true;
          try {
            let { success } = await register(this.Form);
            if (success) {
              this.$message({
                type: "success",
                message: "注册成功"
              });
              this.$router.push({ path: "login" });
            } else {
              this.$message.error("111111");
            }
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        } else {
          console.log("参数验证不合法！");
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="less">
.login-form-layout {
  position: absolute;
  left: 0;
  right: 0;
  width: 360px;
  margin: 140px auto;
  border-top: 10px solid #409eff;
}

.login-title {
  text-align: center;
}

.login-center-layout {
  background: #409eff;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
}
.verify {
  font-size: 10px;
  color: #fff;
  background-color: #409eff;
}
.input-bg /deep/ .el-input-group__append {
  background-color: #409eff;
  color: #fff;
}
.login-form-layout /deep/ .el-input {
  color: #409eff !important;
}
.icon-user {
  width: 16px;
  height: 16px;
}
</style>
